<template>
  <n-form
    ref="formRef"
    :model="model"
    :rules="rulesPwd"
    size="large"
    :show-label="false"
  >
    <n-form-item path="account">
      <n-input
        v-model:value="model.account"
        autofocus
        placeholder="请输入账号"
      />
    </n-form-item>
    <n-form-item path="password">
      <n-input
        v-model:value="model.password"
        type="password"
        show-password-on="mousedown"
        placeholder="请输入密码"
      />
    </n-form-item>
    <n-form-item path="captchaCode">
      <n-input
        v-model:value="model.captchaCode"
        placeholder="请输入验证码"
        @keydown.enter="login"
      />
      <div
        class="w-150 h-40 rd-5 ml-10 cursor-pointer overflow-hidden f-c-c"
        b="1 #e0e0e6"
        @click="getCaptcha"
      >
        <icon-eos-icons-bubble-loading v-if="capLoading" />
        <n-image
          v-else-if="captchaImg"
          class="wh-full"
          :img-props="{ class: 'w-full' }"
          :src="captchaImg"
          preview-disabled
          :fallback-src="ImageBroken"
        />
        <div v-else text-gray>点击获取</div>
      </div>
    </n-form-item>
    <n-space :vertical="true" :size="24">
      <n-button :text="true" @click="toLoginModule('reset-pwd')">
        忘记密码？
      </n-button>
      <n-button
        type="primary"
        size="large"
        block
        round
        :loading="btnLoading"
        @click="login"
      >
        确定
      </n-button>
      <n-button size="large" block round @click="toLoginModule('code-login')">
        验证码登录
      </n-button>
    </n-space>
  </n-form>
</template>

<script setup lang="ts">
import type { FormInst } from "naive-ui";
import { authApi } from "@/api";
import { rulesPwd } from "../common";
import { tokenUtils } from "@/utils";
import { addDynamicRoutes } from "@/router";
import ImageBroken from "@/assets/svg-icon/image-broken.svg";

const route = useRoute();
const router = useRouter();
const formRef = ref<FormInst>();
const capLoading = ref(false);
const btnLoading = ref(false);
const captchaImg = ref("");
const model = ref({
  account: "dongadong",
  password: "159357qazPLM&",
  captchaCode: "",
  key: "",
});

/**
 * 登录模块
 * - pwd-login: 账密登录
 * - code-login: 手机验证码登录
 * - register: 注册
 * - reset-pwd: 重置密码
 * - bind-wechat: 微信绑定
 */
type LoginModule = "pwd-login" | "code-login" | "reset-pwd" | "bind-wechat";

const toLoginModule = (module: LoginModule) => {
  router.push({ query: { ...route.query, module } });
};

const getCaptcha = async () => {
  if (capLoading.value) return;
  capLoading.value = true;
  try {
    const { data } = await authApi.captcha();
    model.value.key = data.key;
    captchaImg.value = data.captchaImg;
  } finally {
    capLoading.value = false;
  }
};

const login = async () => {
  btnLoading.value = true;
  try {
    await formRef.value?.validate();

    const { data } = await authApi.login(model.value);
    tokenUtils.set(data.token);
    window.$message?.success("成功登录");

    await addDynamicRoutes();
    const query = route.query;
    if (query.redirect) {
      const path = query.redirect as string;
      Reflect.deleteProperty(query, "redirect");
      router.push({ path, query });
    } else {
      router.push("/");
    }
  } catch (err) {
    getCaptcha();
    throw err;
  } finally {
    btnLoading.value = false;
  }
};

onMounted(() => {
  getCaptcha();
});
</script>
